<template>
  <div class="purchase-page">
    <!-- 顶部导航 -->
    <div class="nav-header">
      <div class="nav-tabs">
        <span class="active">采购详情</span>
        <span @click="goToSupply">供应详情</span>
      </div>
      <el-button type="primary" plain @click="dialogVisible = true"
        >我想买</el-button
      >
    </div>

    <!-- 筛选区域 -->
    <div class="filter-section">
      <el-form :inline="true" :model="filterForm" ref="filterForm">
        <el-form-item label="资产类型">
          <el-select
            v-model="filterForm.assetType"
            placeholder="请选择"
            v-loading="optionsLoading"
          >
            <el-option value=""></el-option>

            <el-option
              v-for="item in assetTypeOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="项目类型">
          <el-select
            v-model="filterForm.projectType"
            placeholder="请选择"
            v-loading="optionsLoading"
          >
            <el-option value=""></el-option>

            <el-option
              v-for="item in projectTypeOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采购截止日期">
          <el-date-picker
            v-model="filterForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="名称">
          <el-input
            v-model="filterForm.name"
            placeholder="请输入名称"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            @click="
              () => {
                this.currentPage = 1;
                this.handleSearch();
              }
            "
            >搜索</el-button
          >
          <el-button @click="resetFilter">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 数据表格 -->
    <el-table
      :data="tableData"
      stripe
      v-loading="tableLoading"
      element-loading-text="正在加载数据..."
    >
      <el-table-column prop="id" label="编号" width="80"></el-table-column>
      <el-table-column prop="assetType" label="资产类型" width="180">
      </el-table-column>
      <el-table-column
        prop="projectType"
        label="项目类型"
        width="180"
      ></el-table-column>
      <el-table-column
        prop="institutionName"
        label="机构名称"
        width="250"
      ></el-table-column>

      <el-table-column
        prop="tradeQuantity"
        label="采购量(tCO2e)"
        width="140"
      ></el-table-column>
      <el-table-column
        prop="assetUnitPrice"
        label="询价(元/tCO2e)"
        width="140"
      ></el-table-column>
      <el-table-column
        prop="expirationDate"
        label="采购截止日期"
        width="230"
      ></el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button type="text" @click="handleView(scope.row)">查看</el-button>
          <el-button type="text" @click="handleInquiry1(scope.row)"
            >报价</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="totalCount"
      ></el-pagination>
    </div>

    <!-- 我想买弹窗 -->

    <!-- 查看详情弹窗 -->
    <el-dialog title="供应详情" :visible.sync="detailVisible" width="500px">
      <el-form label-width="120px">
        <el-form-item label="询价方">
          <!-- 直接渲染后端返回的汉字 -->
          <el-input v-model="detailForm.institutionName" disabled></el-input>
        </el-form-item>
        <el-form-item label="资产类型">
          <el-input v-model="detailForm.assetType" disabled></el-input>
        </el-form-item>
        <el-form-item label="项目类型">
          <el-input v-model="detailForm.projectType" disabled></el-input>
        </el-form-item>
        <el-form-item label="采购数量(tCO2e)">
          <el-input v-model="detailForm.tradeQuantity" disabled></el-input>
        </el-form-item>
        <el-form-item label="询价(元)">
          <el-input v-model="detailForm.assetUnitPrice" disabled></el-input>
        </el-form-item>
        <el-form-item label="期望交割日期">
          <el-input v-model="detailForm.deliveryTime" disabled></el-input>
        </el-form-item>
        <el-form-item label="期望交割方式">
          <el-input v-model="detailForm.deliveryMethod" disabled></el-input>
        </el-form-item>
        <el-form-item label="期望交割场所">
          <el-input v-model="detailForm.deliveryExchange" disabled></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关闭</el-button>
      </div>
    </el-dialog>
    <!-- 询价弹窗 -->
    <el-dialog
      :title="`询价单-${inquiryForm.institutionName}`"
      :visible.sync="inquiryVisible"
      width="600px"
    >
      <el-form
        ref="inquiryFormRef"
        :model="inquiryForm"
        label-width="150px"
        :rules="inquiryRules"
      >
        <!-- 供应方（只读） -->
        <el-form-item label="供应方">
          <el-input v-model="inquiryForm.institutionName" disabled></el-input>
        </el-form-item>

        <!-- 资产类型（从原数据带出，禁止修改） -->
        <el-form-item label="资产类型">
          <el-input v-model="inquiryForm.assetType" disabled></el-input>
        </el-form-item>

        <!-- 项目领域（从原数据带出，禁止修改） -->
        <el-form-item label="项目领域">
          <el-input v-model="inquiryForm.projectScope" disabled></el-input>
        </el-form-item>

        <!-- 项目类型（从原数据带出，禁止修改） -->
        <el-form-item label="项目类型">
          <el-input v-model="inquiryForm.projectType" disabled></el-input>
        </el-form-item>

        <!-- 采购数量（可编辑） -->
        <el-form-item label="供应数量(tCO2e)" prop="sellerTradeQuantity">
          <el-input
            v-model="inquiryForm.sellerTradeQuantity"
            placeholder="请输入供应数量"
          ></el-input>
        </el-form-item>

        <!-- 询价(¥)（可编辑） -->
        <el-form-item label="报价(¥)" prop="sellerUnitPrice">
          <el-input
            v-model="inquiryForm.sellerUnitPrice"
            placeholder="请输入报价"
          ></el-input>
        </el-form-item>

        <!-- 期望交割日期（可编辑） -->
        <el-form-item label="期望交割日期">
          <el-date-picker
            v-model="inquiryForm.sellerDeliveryTime"
            type="date"
            placeholder="请选择日期"
          ></el-date-picker>
        </el-form-item>

        <!-- 期望交割方式 -->
        <el-form-item label="期望交割方式" prop="sellerDeliveryMethod">
          <el-select
            v-model="inquiryForm.sellerDeliveryMethod"
            placeholder="请选择"
            v-loading="optionsLoading"
          >
            <el-option
              v-for="item in deliveryModeOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="期望交割场所" prop="sellerDeliveryExchange">
          <el-select
            v-model="inquiryForm.sellerDeliveryExchange"
            placeholder="请选择"
            v-loading="optionsLoading"
          >
            <el-option
              v-for="item in deliveryPlaceOptions"
              :key="item"
              :label="item"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="inquiryVisible = false">取消</el-button>
        <el-button type="primary" @click="submitInquiry">报价</el-button>
      </div>
    </el-dialog>

    <el-dialog title="采购单" :visible.sync="dialogVisible" width="600px">
    <el-form :model="form2" label-width="160px"   class="top-aligned-form" >
      <el-form-item label="采购机构*">
        <el-input v-model="form2.institutionName" placeholder="请输入采购机构"></el-input>
      </el-form-item>
      <el-form-item label="采购联系人*">
        <el-input v-model="form2.contactsName" placeholder="请输入采购联系人"></el-input>
      </el-form-item>
      <el-form-item label="联系电话*">
        <el-input v-model="form2.contactsPhone" placeholder="请输入联系电话"></el-input>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="form2.contactsEmail" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="项目领域">
        <el-select v-model="form2.projectScopeCode" placeholder="请选择">
         <el-option
            v-for="item in projectScope"
            :key="item.itemCh"  
            :label="item.itemCh" 
            :value="item.itemValue"
    ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="资产类型">
        <el-select v-model="form2.assetType" placeholder="请选择">
         <el-option
            v-for="item in assetType"
            :key="item.itemCh"  
            :label="item.itemCh" 
            :value="item.itemValue"
    ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="项目类型">
        <el-select v-model="form2.projectType" placeholder="请选择">
          <el-option
            v-for="item in projectType"
            :key="item.itemCh"  
            :label="item.itemCh" 
            :value="item.itemValue"
    ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="采购数量(CO2e)*">
        <el-input v-model="form2.tradeQuantity" placeholder="请输入采购数量"></el-input>
      </el-form-item>
      <el-form-item label="询价(¥)">
        <el-input v-model="form2.assetUnitPrice" placeholder="请输入询价"></el-input>
      </el-form-item>
      <el-form-item label="截止采购日期">
        <el-date-picker
          v-model="form2.expirationDate"
          type="date"
          placeholder="请选择截止采购日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="期望交割日期">
        <el-date-picker
          v-model="form2.deliveryTime"
          type="date"
          placeholder="请选择期望交割日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="期望交割方式">
  <el-select v-model="form2.deliveryMethod" placeholder="请选择">
   <el-option
      v-for="item in deliveryMethod"
      :key="item.itemCh"  
      :label="item.itemCh" 
      :value="item.itemValue"
    ></el-option>
  </el-select>
</el-form-item>

<el-form-item label="期望交割场所">
  <el-select v-model="form2.deliveryExchange" placeholder="请选择">
   <el-option
      v-for="item in deliveryExchange"
      :key="item.itemCh"  
      :label="item.itemCh" 
      :value="item.itemValue"
    ></el-option>
  </el-select>
</el-form-item>

    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取消</el-button>
      <el-button type="primary" @click="handlecaiSubmit">提交</el-button>
    </div>
  </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 验证手机号
    const validatePhone = (rule, value, callback) => {
      const reg = /^1[3-9]\d{9}$/;
      if (!value) {
        return callback(new Error("请输入联系电话"));
      }
      if (!reg.test(value)) {
        return callback(new Error("请输入正确的手机号"));
      }
      callback();
    };

    // 验证邮箱
    const validateEmail = (rule, value, callback) => {
      if (!value) {
        return callback(); // 非必填项
      }
      const reg = /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;
      if (!reg.test(value)) {
        return callback(new Error("请输入正确的邮箱格式"));
      }
      callback();
    };

    // 验证数字（大于0）
    const validateNumber = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请输入数值"));
      }
      if (isNaN(value) || parseFloat(value) <= 0) {
        return callback(new Error("请输入大于0的数字"));
      }
      callback();
    };

    return {
      
      dialogVisible: false,
      // 我要买的form上传到后端用
      form2: {
        publisherId: '',
        // 机构名称（对应institution_name）
        institutionName: '',
        // 联系人姓名（对应contacts_name）
        contactsName: '',
        // 联系人手机（对应contacts_phone）
        contactsPhone: '',
        // 联系人邮箱（对应contacts_email）
        contactsEmail: '',
        // 项目领域（对应project_scope_code）
        projectScopeCode: '',
        // 资产类型（对应asset_type）
        assetType: '',
        // 项目类型（对应project_type）
        projectType: '',
        // 交易量（对应trade_quantity）
        tradeQuantity: '',
        // 资产单价（对应asset_unit_price）
        assetUnitPrice: '',
        // 交易截止日期（对应expiration_date）
        expirationDate: '',
        // 期望交割时间（对应delivery_time）
        deliveryTime: '',
        // 期望交割方式（对应delivery_method）
        deliveryMethod: '',
        // 交割场所
        deliveryExchange: '',
      },
      user: JSON.parse(localStorage.getItem("user") || "{}"),
      inquiryRules: {
        sellerTradeQuantity: [
          { required: true, message: "请输入供应数量", trigger: "submit" }, // 仅提交时触发
        ],
        sellerUnitPrice: [
          { required: true, message: "请输入报价", trigger: "submit" }, // 仅提交时触发
        ],
      },
      deliveryModeOptions: [], // 交割方式列表
      deliveryPlaceOptions: [], // 交割场所列表
      optionsLoading: false,
      // 筛选表单数据
      filterForm: {
        assetType: "",
        projectType: "",
        dateRange: [],
      },
      deliveryMethods: [], // 交割方式列表
      deliveryExchanges: [], // 交割场所列表
      loadingDeliveryData: false, // 加载状态
      // 表格数据
      tableData: [],
      tableLoading: false,
      totalCount: 0,
      currentPage: 1,
      pageSize: 10,

      // 弹窗控制
      purchaseVisible: false,
      detailVisible: false,
      inquiryVisible: false,

      // 采购表单数据
      purchaseForm: {
        institution: "当前登录机构", // 实际应用中应从登录信息获取
        contact: "",
        phone: "",
        email: "",
        projectArea: "all",
        assetType: "all",
        projectType: "all",
        amount: "",
        price: "",
        purchaseEndDate: "",
        expectedDeliveryDate: "",
        deliveryMethod: "all",
        deliveryLocation: "all",
      },

      // 采购表单验证规则
      purchaseRules: {
        contact: [
          { required: true, message: "请输入采购联系人", trigger: "blur" },
        ],
        phone: [{ required: true, validator: validatePhone, trigger: "blur" }],
        email: [{ validator: validateEmail, trigger: "blur" }],
        amount: [
          { required: true, validator: validateNumber, trigger: "blur" },
        ],
      },
      
      // 详情表单数据
      detailForm: {
        id: "",
        projectType: "",
        projectTypeText: "",
        institution: "",
        assetType: "",
        assetTypeText: "",
        amount: "",
        price: "",
        endDate: "",
        description: "",
        contactInfo: "",
      },
      projectTypeOptions: [],
      assetTypeOptions: [],
      inquiryForm: {
        buyerDeliveryMethod: "", // 关键：显式初始化
        tradeQuoteId: "",
        buyerId: "",
        sellerId: "",
        buyerPhone:"",
        dialogue: "",
        sellerPhone:"",
        projectType:"",
        expirationDate: "",
        buyerName: "",
        sellerName: "",
        sellerTradeQuantity: "",
        sellerUnitPrice: "",
        sellerDeliveryTime: "",
        sellerDeliveryExchange: "",
        sellerDeliveryMethod: "",
        buyerDeliveryExchange: "",
        institutionName: "", // 供应方（从表格行数据赋值）
        assetType: "", // 资产类型
        projectScope: "", // 项目领域
        projectType: "", // 项目类型
        buyerTradeQuantity: "", // 采购数量
        buyerUnitPrice: "", // 询价
        buyerDeliveryTime: "", // 期望交割日期
        assetType: "",
      },
    };
  },

  created() {
    // 页面初始化时加载数据
    this.handleSearch();
    this.loadDeliveryData();
  },
  mounted() {
    this.loadSelectorData();
   this.form2.publisherId = this.user.tenantId || '';
    this.initDeliveryOptions(); // 新增获取交割方式数据的调用
    this.initTypeOptions(); // 新增获取交割方式数据的调用
  },
  methods: {
     // 提交我要买
    handlecaiSubmit() {
      console.log('这是form2', this.form2)

      if (this.form2.assetType === '0140000000') {
        this.form2.assetType = ''
      }
      if (this.form2.projectType === '0040000000') {
        this.form2.projectType = ''
      }
      if (this.form2.projectScopeCode === '0030000000') {
        this.form2.projectScopeCode = ''
      }
      this.$request.post('/trade/carbonTradeQuote/addBuy', this.form2).then(res => {
        if (res.code === 200) {
          this.$message.success('采购清单提交成功');
          this.dialogVisible = false;
        } else {
          this.$message.error(res.msg || '提交失败');
        }
      })
    },
    async fetchDeliveryOptions(type) {
      this.optionsLoading = true;
      try {
        // 调用后端接口，传递type参数（路径参数）
        const res = await this.$request.get(
          `/trade/carbonTradeQuote/getDeliveryMethod/${type}`
        );
        // 假设后端返回格式：{ success: true, data: [] }（根据你的ApiResult结构调整）
        if (res.code == 200) {
          return res.data; // 返回查询到的列表
        } else {
          this.$message.warning("获取数据失败");
          return [];
        }
      } catch (error) {
        console.error(`获取${type}失败：`, error);
        return [];
      } finally {
        this.optionsLoading = false;
      }
    },
    async initTypeOptions() {
      // 1. 获取项目类型（type=projectType）
      const modes = await this.fetchDeliveryOptions("projectType");
      this.projectTypeOptions = modes;
      // 2. 获取资产类型（type=assetType）
      const places = await this.fetchDeliveryOptions("assetType");
      this.assetTypeOptions = places;
    },
    handleSizeChange(val) {
      this.pageSize = val; // 更新每页条数
      this.handleSearch(); // 重新加载表格数据
    },

    // 处理页码变更
    handleCurrentChange(val) {
      this.currentPage = val; // 更新当前页码
      this.handleSearch(); // 重新加载表格数据
    },
     loadSelectorData() {
      this.$request.get('/assets/carbonCreditAssets/querySelector').then(res => {
        if (res.code === 200) {
          this.certificationCriteria = res.data.certificationList
          this.transactionStatus = res.data.transactionStatusList
          this.assetsStatus = res.data.assetsStatusList
          this.projectScope = res.data.projectScopeList
          this.assetType = res.data.assetTypeList
          this.projectType = res.data.projectTypeList
          this.deliveryMethod = res.data.deliveryMethodList
          this.deliveryExchange = res.data.deliveryExchangeList
        }
      })
    },
    // 分别获取交割方式和场所
    async initDeliveryOptions() {
      // 1. 获取交割方式（type=deliveryMethod）
      const modes = await this.loadDeliveryData("deliveryMethod");
      this.deliveryModeOptions = modes;
      // 2. 获取交割场所（type=deliveryExchange）
      const places = await this.loadDeliveryData("deliveryExchange");
      this.deliveryPlaceOptions = places;
    },
    // 加载交割方式和场所数据
    async loadDeliveryData(type) {
      this.optionsLoading = true;
      try {
        // 调用后端接口，传递type参数（路径参数）
        const res = await this.$request.get(
          `/trade/carbonTradeQuote/getDeliveryMethod/${type}`
        );
        // 假设后端返回格式：{ success: true, data: [] }（根据你的ApiResult结构调整）
        if (res.code == 200) {
          return res.data; // 返回查询到的列表
        } else {
          this.$message.warning("获取数据失败");
          return [];
        }
      } catch (error) {
        console.error(`获取${type}失败：`, error);
        return [];
      } finally {
        this.optionsLoading = false;
      }
    },
    // 跳转到供应详情页面
    goToSupply() {
      // 实际应用中应使用路由跳转
      this.$router.push("/trade/Quote/sellQuote");
    },

    // 打开采购弹窗
    openPurchaseDialog() {
      this.purchaseVisible = true;
      // 重置表单
      this.$nextTick(() => {
        this.$refs.purchaseFormRef.resetFields();
      });
    },

    // 处理搜索（修改为JSON格式传参）
    async handleSearch() {
      this.searchLoading = true;
      try {
        // 处理日期范围（替换可选链语法）
        let startDate = undefined;
        let endDate = undefined;
        if (
          this.filterForm.dateRange &&
          this.filterForm.dateRange.length === 2
        ) {
          startDate = this.filterForm.dateRange[0];
          endDate = this.filterForm.dateRange[1];
        }

        // 构建JSON格式的请求参数
        const requestData = {
          assetType: this.filterForm.assetType || undefined,
          projectType: this.filterForm.projectType || undefined,
          keyword: this.filterForm.name || undefined,
          expirationDateStart: startDate, // 使用上面处理后的日期
          expirationDateEnd: endDate,
          currentPage: this.currentPage,
          pageSize: this.pageSize,
        };

        const res = await this.$request.post(
          "/trade/carbonTradeQuote/handleSearchB",
          requestData
        );
        if (res.code === 200) {
          this.tableData = res.data.list;
          this.totalCount = res.data.total;
        } else {
          this.$message.warning("搜索失败: " + (res.msg || "未知错误"));
        }
      } catch (error) {
        console.error("搜索请求失败:", error);
        this.$message.error("网络错误，搜索失败");
      } finally {
        this.searchLoading = false;
      }
    },

    // 重置筛选条件（修改后）
    resetFilter() {
      // 重置表单所有字段
      if (this.$refs.filterForm) {
        this.$refs.filterForm.resetFields();
      }

      // 强制清除所有筛选条件
      this.filterForm = {
        assetType: "",
        projectType: "",
        dateRange: [],
        name: "",
      };

      // 重置页码并重新加载数据
      this.currentPage = 1;
      this.handleSearch();
    },

    // ...其他原有方法保持不变

    // 查看详情
    handleView(row) {
      this.detailVisible = true;
      this.detailForm = { ...row };
    },
    // 处理询价
    // handleInquiry(row) {
    //   this.inquiryVisible = true;
    //   this.inquiryForm =  { ...row };
    //   this.inquiryForm.projectName = `${
    //     row.institution
    //   } - ${this.getAssetTypeText(row.assetType)}`;

    //   // 重置表单
    //   this.$nextTick(() => {
    //     this.$refs.inquiryFormRef.resetFields();
    //   });
    // },
    handleInquiry1(row) {
      this.inquiryVisible = true;
      this.inquiryForm = {
        buyerDeliveryMethod: "",
        buyerDeliveryExchange: "",
        institutionName: "",
        assetType: "",
        projectScope: "",
        projectType: "",
        buyerTradeQuantity: "",
        buyerUnitPrice: "",
        buyerDeliveryTime: "",
        buyerId: "",
        sellerId: "",
        sellerTradeQuantity: "",
        sellerUnitPrice: "",
        sellerDeliveryTime: "",
        sellerDeliveryExchange: "",
        sellerDeliveryMethod: "",
        dialogue: "",
        buyerPhone:"",
        sellerPhone:"",
        projectType:"",
        assetType: "",
        buyerName: "",
        sellerName: "",
        expirationDate: "",
      };
      // 2. 逐项赋值，避免覆盖响应式对象
      this.inquiryForm.institutionName = row.institutionName || "";
      this.inquiryForm.assetType = row.assetType || "";
      this.inquiryForm.projectScope = row.projectScope || "";
      this.inquiryForm.projectType = row.projectType || "";
      (this.inquiryForm.sellerId = this.user.tenantId),
        (this.inquiryForm.buyerId = row.publisherId || ""),
        (this.inquiryForm.buyerTradeQuantity = row.tradeQuantity || ""),
        (this.inquiryForm.buyerUnitPrice = row.assetUnitPrice || ""),
        (this.inquiryForm.buyerDeliveryTime = row.deliveryTime || ""),
        (this.inquiryForm.buyerDeliveryExchange = row.deliveryExchange || ""),
        (this.inquiryForm.buyerDeliveryMethod = row.deliveryMethod || ""),
        (this.inquiryForm.dialogue =
          row.institutionName + "_" + this.user.accountName),
        (this.inquiryForm.assetType = row.assetType);
      (this.inquiryForm.buyerName = row.institutionName),
        (this.inquiryForm.sellerName = this.user.accountName),
        (this.inquiryForm.expirationDate = row.expirationDate),
        this.inquiryForm.projectType = row.projectType,
                this.inquiryForm.buyerPhone = row.contactsPhone,
        this.inquiryForm.sellerPhone = this.user.phone,
        this.$nextTick(() => {
          this.$refs.inquiryFormRef.resetFields();
        });
    },
    

    submitInquiry() {
      // 先执行表单校验
      this.$refs.inquiryFormRef.validate((valid) => {
        if (valid) {
          // 校验通过，准备提交数据
          this.tableLoading = true; // 显示加载状态

          // 1. 整理表单数据（直接使用 inquiryForm 整个对象，包含所有字段）
          const submitData = {
            ...this.inquiryForm,
            // 若需补充额外字段（如当前时间、操作人），可在此添加
            // submitTime: new Date().format('yyyy-MM-dd HH:mm:ss'),
            // operator: this.user.username || ''
          };

          // 2. 调用后端接口提交数据
          this.$request
            .post("/trade/carbonTradePrice/addB", submitData) // 替换为实际接口路径
            .then((res) => {
              // 接口请求成功
              if (res.code === 200) {
                this.$message.success("报价提交成功，我们会尽快与您联系！");
                this.inquiryVisible = false; // 关闭弹窗
                this.handleSearch(); // 可选：刷新列表数据
              } else {
                // 接口返回非成功状态（如业务错误）
                this.$message.error(res.msg);
              }
            })
            .catch((error) => {})
            .finally(() => {
              // 无论成功/失败，都关闭加载状态
              this.tableLoading = false;
            });
        } else {
          // 校验失败，提示用户完善表单
          this.$message.error("请检查表单填写是否正确，必填项不能为空！");
          return false;
        }
      });
    },
    loadTableData() {
      this.tableLoading = true;
      // 使用项目封装的this.$request发送GET请求
      this.$request
        .get("/trade/carbonTradeQuote/getSellList", {
          // 接口不需要参数，这里传空对象或省略params
          params: {},
        })
        .then((res) => {
          console.log("这是全部供应数据", res);
          // 假设接口返回格式为{code: 200, data: [], total: 总数}
          if (res.code === 200) {
            // 直接使用返回的驼峰式字段数据
            this.tableData = res.data;
            // 假设总条数在res.total字段，根据实际接口调整
            this.totalCount = res.data.total;
          } else {
            // 接口返回非成功状态时的处理
            this.$message.warning("获取数据失败：" + (res.msg || "未知错误"));
            this.tableData = [];
            this.totalCount = 0;
          }
          this.tableLoading = false;
        })
        .catch((error) => {
          console.error("请求供应数据出错：", error);
          this.$message.error("网络错误，获取数据失败");
          this.tableData = [];
          this.totalCount = 0;
          this.tableLoading = false;
        });
    },

   
    handleDialogClose(done) {
      // 示例：关闭前询问用户是否确认，防止误操作
      this.$confirm("确定要关闭吗？未保存的内容将会丢失。")
        .then(() => {
          // 用户确认关闭，调用done()完成关闭
          done();
        })
        .catch(() => {
          // 用户取消关闭，不执行任何操作（弹窗保持打开）
        });
    },
    // 获取资产类型文本
    getAssetTypeText(type) {
      const typeMap = {
        forestry: "林业碳汇",
        photovoltaic: "光伏减排",
        windPower: "风电减排",
        hydropower: "水电减排",
      };
      return typeMap[type] || type;
    },
  },
};
</script>

<style scoped>
.purchase-page {
  padding: 20px;
  background-color: #fff;
  min-height: calc(100vh - 40px);
}

.nav-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.nav-tabs {
  display: flex;
  gap: 30px;
  font-size: 16px;
}

.nav-tabs span {
  cursor: pointer;
  padding: 5px 0;
  position: relative;
}

.nav-tabs .active {
  color: #409eff;
  font-weight: 500;
}

.nav-tabs .active::after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background-color: #409eff;
}

.filter-section {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 确保弹窗中的表单样式正确 */
.el-dialog__body {
  padding: 20px;
  max-height: 60vh;
  overflow-y: auto;
}

.dialog-footer {
  text-align: right;
}

.el-button--primary {
  background-color: #67c23a;
  border-color: #67c23a;
  color: white;
}

.el-button--primary:hover,
.el-button--primary:focus {
  background-color: #67c23a;
  border-color: #67c23a;
}

/* 表格样式优化 */
::v-deep .el-table th {
  background-color: #f5f7fa;
  font-weight: 500;
}

::v-deep .el-table td,
::v-deep .el-table th {
  text-align: center;
}

/* 响应式调整 */
@media screen and (max-width: 1200px) {
  .nav-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 15px;
  }

  .filter-section {
    overflow-x: auto;
    padding-bottom: 15px;
  }

  .el-dialog {
    width: 90% !important;
  }
}
</style>
